package net.lanelife.casino.caipiao.job.handler;

import java.util.HashMap;
import java.util.Map;

import net.lanelife.casino.caipiao.entity.BankTransactionDetail;
import net.lanelife.casino.caipiao.entity.Job;
import net.lanelife.casino.caipiao.entity.RechargeRecord;
import net.lanelife.casino.caipiao.entity.TransactionDetail;
import net.lanelife.casino.caipiao.entity.User;
import net.lanelife.casino.caipiao.job.info.RechargeJobInfo;
import net.lanelife.casino.caipiao.service.api.IRechargeRecordService;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 充值任务处理器
 * @author Lane
 *
 */
@Component
public class RechargeJobHandler extends TransactionJobHandler {
	
	@Autowired
	private IRechargeRecordService rechargeRecordService;
	
	@Transactional(rollbackFor = Exception.class)
	public void handle(Job job) throws Exception {
		
		final RechargeJobInfo       jobInfo = job.readInfo(RechargeJobInfo.class);                     // 任务信息
		final RechargeRecord rechargeRecord = rechargeRecordService.find(jobInfo.getRID());            // 充值记录
		final User                     user = rechargeRecord.getUser();                                // 充值用户
		final LocalDate          reportDate = new LocalDate(jobInfo.getTIME());                        // 报表日期
		final Double                 amount = rechargeRecord.getAmount();                              // 充值金额
		final Double                    fee = rechargeRecord.getFee();                                 // 手续费
		Map<String, Object>      properties = new HashMap<String, Object>();                           // 更新字段
		
		switch (rechargeRecord.getWay()) {
		case OP: // 在线支付
			properties.put("RECHARGE_TIMES_P", 1);
			properties.put("RECHARGE_TOTAL_P", amount);
			properties.put("RECHARGE_FEE_P", fee);
			break;
		case BT: // 网银转账
			properties.put("RECHARGE_TIMES_T", 1);
			properties.put("RECHARGE_TOTAL_T", amount);
			properties.put("RECHARGE_FEE_T", fee);
			break;
		}
		
		saveTransactionDetail(
				user, 
				rechargeRecord.getBillNo(), 
				TransactionDetail.TransactionDirection.IN, 
				TransactionDetail.TransactionType.IN_RECHARGE, 
				new DateTime(jobInfo.getTIME()), 
				amount + fee, 
				jobInfo.getUPB(), 
				jobInfo.getUCB()
		);
		
		saveBankTransactionDetail(
				BankTransactionDetail.TransactionDirection.IN, 
				BankTransactionDetail.SourceUsesType.SK, 
				new DateTime(jobInfo.getTIME()), 
				rechargeRecord.getPayeeBankName(), 
				rechargeRecord.getPayeeAccountName(), 
				rechargeRecord.getPayeeAccountNo(), 
				rechargeRecord.getPayerBankName(), 
				rechargeRecord.getPayerAccountName(), 
				rechargeRecord.getPayerAccountNo(), 
				amount, 
				fee, 
				jobInfo.getBCB(), 
				user.getUserName()
		);
		
		updateTransactionStatistics(user, reportDate, properties);
		
	}

}
